#encoding:utf-8
import os
import sys
import shutil
import commands
import logging  
import md5
import time
import sdk_util

from sdk_log import LOG

# 在apk中插入代码 
def inject(apkfile, meta_data, outApk, bangcleplugin, public_path, plugins_json, tray_name):
    ''' 在apk中插入代码,不会返回异常，如果成功，就把输出的apk写入到outApk
        如果失败在outApk的位置就不会有apk
        不论失败与否不会留下任何临时文件
    '''
    LOG.info(apkfile + ":begin inject")

    try:

        # 1.先解压 apk文件
        m = md5.new(apkfile + str(time.time()))
        TMPDIR = os.path.join(os.path.dirname(apkfile), m.hexdigest())
        LOG.info(apkfile + ":1 unzip_apk:" + apkfile +  "=>" + TMPDIR)
        sdk_util.unzip_apk(apkfile,TMPDIR)

        # 2 修改dex文件
        # 2.1解开classes.dex到smali目录
        LOG.info(apkfile + ":2.1 unzip_classes the classes.dex")
        classes_dex_path = os.path.join(TMPDIR, "classes.dex")
        classes_smali_dir = os.path.join(TMPDIR, "smali")
        sdk_util.unzip_classes(classes_dex_path, classes_smali_dir)

        #2.2 获取主类名
        main_activitys = sdk_util.getpackage_lanuch(os.path.join(TMPDIR,"AndroidManifest.xml"))
        LOG.info(apkfile + ":2.2 get the MainActivitys:" + main_activitys)

        #2.3 在mainactivity里添加app_start的代码
        LOG.info(apkfile + ":2.3 add app_start code into the MainActivity")

        if main_activitys == "":
            raise Exception('no MainActivity')
        else:
            for main_activity in main_activitys.split("||"):
                sdk_util.inject_smali(classes_smali_dir, main_activity)


        # 2.4 复制neo到目标smali中
        LOG.info(apkfile+":2.4.1 copy neo folder to smali")
        sdk_util.copytree(os.path.join(public_path, "smali/bangsdk/neo"),os.path.join(classes_smali_dir, "neo"))

        # 2.4.2千速smali到目标smali中
        if tray_name.lower() == 'qiansusdk':
            LOG.info(apkfile+":2.4.2 copy qiansu folder to smali")
            sdk_util.copytree(os.path.join(public_path, "smali/qiansusdk/com"),os.path.join(classes_smali_dir, "com"))    

        
        # 2.5 生成新的dex文件
        LOG.info(apkfile+":2.5 make new class_dex")
        sdk_util.pack_dex(classes_smali_dir, os.path.join(TMPDIR,"classes_new.dex"))
        shutil.move(os.path.join(TMPDIR,"classes_new.dex"), os.path.join(TMPDIR, "classes.dex"))
        shutil.rmtree(classes_smali_dir)


        # 3 修改manifest
        LOG.info(apkfile + ":3 modify manifest")

        inMF = os.path.join(TMPDIR, "AndroidManifest.xml")
        outMF = os.path.join(TMPDIR, "AndroidManifest_new.xml")
        sdk_util.repack_AndroidMF(tray_name, inMF,outMF, meta_data)
        shutil.move(outMF, inMF)


        # 4 重新打包apk并把bangcleplugin里的内容放到assets里,并把androidmanif.xml和class.dex用tmp里的替换掉

        sdk_util.zip_apk(apkfile,outApk, bangcleplugin, TMPDIR, public_path, plugins_json, tray_name)
        LOG.info(apkfile + ":4 success:"+outApk)

    except Exception,e:

        LOG.warning(apkfile + ":" + str(e))
        try:
            os.remove(outApk)
        except Exception, e:
            pass
        
    finally:

        # 5.移除临时目录
        try:
            shutil.rmtree(TMPDIR)
            LOG.info(apkfile + ":5 remove TMPDIR:" + TMPDIR)
        except Exception, e:
            pass 


